<template>
  <div class="app-container">
    <div class="filter-container">
      <!-- <el-input v-model="listQuery.title" placeholder="Title" style="width: 200px;" class="filter-item" @keyup.enter.native="handleFilter" />
      <el-select v-model="listQuery.importance" placeholder="Imp" clearable style="width: 90px" class="filter-item">
        <el-option v-for="item in importanceOptions" :key="item" :label="item" :value="item" />
      </el-select>
      <el-select v-model="listQuery.type" placeholder="Type" clearable class="filter-item" style="width: 130px">
        <el-option v-for="item in familyTypeOptions" :key="item.key" :label="item.display_name+'('+item.key+')'" :value="item.key" />
      </el-select>
      <el-select v-model="listQuery.sort" style="width: 140px" class="filter-item" @change="handleFilter">
        <el-option v-for="item in sortOptions" :key="item.key" :label="item.label" :value="item.key" />
      </el-select>
      <el-button v-waves class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">
        Search
      </el-button> -->
      <el-button
        class="filter-item"
        style="margin-left: 10px;"
        type="primary"
        icon="el-icon-edit"
        @click="handleCreate"
      >添加</el-button>
      <el-button
        v-waves
        :loading="downloadLoading"
        class="filter-item"
        type="primary"
        icon="el-icon-download"
        @click="handleDownload"
      >导出查询结果</el-button>
      <!-- <el-checkbox v-model="showReviewer" class="filter-item" style="margin-left:15px;" @change="tableKey=tableKey+1">
        reviewer
      </el-checkbox>-->
    </div>

    <el-table
      :key="tableKey"
      v-loading="listLoading"
      :data="list"
      border
      fit
      size="mini"
      highlight-current-row
      style="width: 100%;"
      row-key="id"
      :lazy="lazy"
      :load="load"
    >
      <el-table-column
        label="部门编码"
        prop="code"
        align="center"
      ></el-table-column>
      <el-table-column
        label="部门名称"
        align="center"
        prop="name"
      ></el-table-column>
      <el-table-column
        label="行政区域名称"
        align="center"
        prop="regionFullname"
      ></el-table-column>
      <el-table-column
        label="部门类型"
        align="center"
        prop="departmentType"
      ></el-table-column>
      <el-table-column
        label="是否启用"
        align="center"
        prop="enabled"
      >
        <template slot-scope="scope">
          <span>{{ scope.row.enabled ? '是':'否' }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="显示顺序"
        align="center"
        prop="displayOrder"
      ></el-table-column>
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="{row}">
          <el-button
            type="primary"
            size="mini"
            @click="handleUpdate(row)"
          >编辑</el-button>
          <el-button
            size="mini"
            type="danger"
            @click="handleModifyStatus(row,'deleted')"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="listQuery.page"
      :limit.sync="listQuery.limit"
      @pagination="getList"
    />

    <el-dialog
      :title="textMap[dialogStatus]"
      :visible.sync="dialogFormVisible"
    >
      <el-form
        ref="dataForm"
        :rules="rules"
        :model="temp"
        label-position="left"
        label-width="120px"
        style="width: 400px; margin-left:50px;"
      >
        <el-form-item
          label="部门编码"
          prop="code"
        >
          <el-input
            v-model="temp.code"
            placeholder="请输入部门编码"
          />
        </el-form-item>
        <el-form-item
          label="部门名称"
          prop="name"
        >
          <el-input
            v-model="temp.name"
            placeholder="请输入部门名称"
          />
        </el-form-item>
        <el-form-item
          label="上级机构"
          prop="family"
        >
          <el-cascader
            v-model="temp.family"
            placeholder="试试搜索上级机构"
            :options="familyTypeOptions"
            :props="optionProps"
            filterable
            change-on-select
            @change="handleCascaderChange2"
          ></el-cascader>
        </el-form-item>
        <el-form-item
          label="行政区域名称"
          prop="regionFamily"
        >
          <el-cascader
            v-model="temp.regionFamily"
            placeholder="试试搜索行政区域"
            :options="regionFamilyTypeOptions"
            :props="optionProps"
            filterable
            change-on-select
            @change="handleCascaderChange1"
          ></el-cascader>
        </el-form-item>
        <el-form-item
          label="部门类型"
          prop="departmentType"
        >
          <el-select
            v-model="temp.departmentType"
            class="filter-item"
            placeholder="请选择"
          >
            <el-option
              v-for="item in departmentTypeOptions"
              :key="item.value"
              :label="item.name"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item
          label="是否启用"
          prop="enabled"
        >
          <el-radio
            v-model="temp.enabled"
            :label="true"
          >启用</el-radio>
          <el-radio
            v-model="temp.enabled"
            :label="false"
          >不启用</el-radio>
        </el-form-item>
        <el-form-item
          label="显示顺序"
          prop="displayOrder"
        >
          <el-input-number
            v-model="temp.displayOrder"
            controls-position="right"
            :min="0"
          ></el-input-number>
        </el-form-item>
      </el-form>
      <div
        slot="footer"
        class="dialog-footer"
      >
        <el-button @click="dialogFormVisible = false">取消</el-button>
        <el-button
          type="primary"
          @click="dialogStatus==='create'?createData():updateData()"
        >确认</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import * as departmentApis from '@/api/department'
  import * as regionApis from '@/api/region'
  import * as baseApis from '@/api/base'
  import waves from '@/directive/waves' // waves directive
  import { parseTime } from '@/utils'
  import Pagination from '@/components/Pagination' // secondary package based on el-pagination

  export default {
    name: 'Department',
    components: { Pagination },
    directives: { waves },
    data () {
      return {
        tableKey: 0,
        list: null,
        total: 0,
        listLoading: true,
        listQuery: {
          page: 1,
          limit: 20,
          importance: undefined,
          title: undefined,
          type: undefined,
          sort: '+id'
        },
        importanceOptions: [1, 2, 3],
        familyTypeOptions: [],
        regionFamilyTypeOptions: [],
        sortOptions: [{ label: 'ID Ascending', key: '+id' }, { label: 'ID Descending', key: '-id' }],
        showReviewer: false,
        temp: {
          code: '',
          name: '',
          family: [],
          regionFamily: [],
          departmentType: '',
          enabled: false,
          displayOrder: ''
        },
        dialogFormVisible: false,
        dialogStatus: '',
        textMap: {
          update: '编辑',
          create: '新建'
        },
        departmentTypeOptions: [],
        rules: {
          family: [{ required: true, message: '请选择行政区域名称', trigger: ['change', 'blur'] }],
          code: [{ required: true, message: '请输入部门编码', trigger: 'blur' }],
          name: [{ required: true, message: '请输入部门名称', trigger: 'blur' }],
          regionFamily: [{ required: true, message: '请输入上级机构', trigger: 'blur' }]
        },
        downloadLoading: false,
        lazy: false,
        optionProps: {
          value: 'id',
          label: 'name'
        }
      }
    },
    created () {
      this.getList()
      regionApis.fetchList().then(({ data }) => {
        this.regionFamilyTypeOptions = data.children
      })
      baseApis.fetchEnumList('DEPARTMENT_TYPE').then(({ data }) => {
        this.departmentTypeOptions = Object.entries(data).map(item => {
          return {
            name: item[1],
            value: item[0],
          }
        })
      })
    },
    methods: {
      getList () {
        this.listLoading = true
        departmentApis.fetchList().then(({ data }) => {
          this.familyTypeOptions = data.children
          this.list = this._formatList(data.children)
          this.$nextTick(() => {
            this._expandAll()
          })
          this.listLoading = false
        })
      },
      handleCascaderChange1 (val) {
        this.temp.regionId = val[val.length - 1]
      },
      handleCascaderChange2 (val) {
        this.temp.parentId = val[val.length - 1]
      },
      _expandAll () {
        if (this.lazy) return
        const Doms = document.querySelectorAll('.app-container .el-table__expand-icon')
        for (let index = 0; index < Doms.length; index++) {
          const element = Doms[index];
          element.click()
        }
      },
      _formatList (list) {
        if (!this.lazy) return list
        list.forEach(child => {
          if (child.children) {
            delete child.children
            // child.family = child.family.map(item => +item)
            console.log(child.family);
            child.hasChildren = true
          }
        })
        return list
      },
      handleFilter () {
        // this.listQuery.page = 1
        this.getList()
      },
      handleModifyStatus (row, status) {
        departmentApis.del(row.id).then(() => {
          this.$message({
            message: '刪除成功！',
            type: 'success'
          })
          this.getList()
        })
      },
      resetTemp () {
        this.temp = {
          code: '',
          name: '',
          family: [],
          regionFamily: [],
          departmentType: '',
          enabled: false,
          displayOrder: ''
        }
      },
      handleCreate () {
        this.resetTemp()
        this.dialogStatus = 'create'
        this.dialogFormVisible = true
        this.$nextTick(() => {
          this.$refs['dataForm'].clearValidate()
        })
      },
      createData () {
        this.$refs['dataForm'].validate((valid) => {
          if (valid) {
            let temp = this.temp
            temp.fullname && delete temp.fullname
            temp.family && delete temp.family
            temp.regionFullname && delete temp.regionFullname
            temp.regionFamily && delete temp.regionFamily

            departmentApis.create(temp).then(() => {
              this.dialogFormVisible = false
              this.$notify({
                title: 'Success',
                message: '创建成功！',
                type: 'success',
                duration: 2000
              })
              this.getList()
            })
          }
        })
      },
      handleUpdate (row) {
        this.temp = Object.assign({}, row) // copy obj
        this.dialogStatus = 'update'
        this.dialogFormVisible = true
        this.$nextTick(() => {
          this.$refs['dataForm'].clearValidate()
        })
      },
      updateData () {
        this.$refs['dataForm'].validate((valid) => {
          if (valid) {
            let temp = this.temp
            temp.fullname && delete temp.fullname
            temp.family && delete temp.family
            temp.regionFullname && delete temp.regionFullname
            temp.regionFamily && delete temp.regionFamily
            const tempData = Object.assign({}, temp)
            departmentApis.update(tempData).then(() => {
              this.dialogFormVisible = false
              this.$notify({
                title: 'Success',
                message: '更新成功！',
                type: 'success',
                duration: 2000
              })
              this.getList()
            })
          }
        })
      },
      handleDownload () {
        this.downloadLoading = true
        import('@/vendor/Export2Excel').then(excel => {
          const tHeader = ['部门编码', '部门名称', '行政区域名称', '部门类型', '是否启用', '显示顺序']
          const filterVal = ['code', 'name', 'regionFullname', 'departmentType', 'enabled', 'displayOrder']
          const data = this.formatJson(filterVal, this.list)
          // toFixed二三级没有处理
          excel.export_json_to_excel({
            header: tHeader,
            data,
            filename: '责任部门'
          })
          this.downloadLoading = false
        })
      },
      formatJson (filterVal, jsonData) {
        return jsonData.map(v => filterVal.map(j => {
          return v[j]
        }))
      },
      load (tree, treeNode, resolve) {
        departmentApis.fetchChildList(tree.id).then(({ data }) => {
          let res = this._formatList(data)
          resolve(res)
        })
      }
    }
  }
</script>
